import axios from 'axios'
import { message } from 'ant-design-vue'

const service = axios.create({
    // baseURL: '/api',
    baseURL: window.httpUrl,
    timeout: 500000 // request timeout

})

service.interceptors.request.use(
  (config) => {

    let url = config.url
    if (config.method === 'get') {
      url.indexOf('?') === -1 ? config.url = url + '?timeStamp=' + (new Date().getTime()) : config.url = url + '&timeStamp=' + (new Date().getTime())
    }

    let token = ''
    let tokenInfo = ''
    if (sessionStorage.getItem('financial-token')) {
      tokenInfo = JSON.parse(sessionStorage.getItem('financial-token'))
      token = tokenInfo.tokenHeader + tokenInfo.token
    }
    token ? config.headers['Authorization'] = token : null

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data

    if (res.code === '0') {
      if (res.msg === '当前登录已失效，请重新登录!') {
            //获取当前地址
            let publicUrl =
              location.protocol +
              "//" +
              location.hostname +
              (location.port === 80 ? "" : ":" + location.port);
            //单点登录地址
            let authLoginUrl = window.authLoginUrl
            // window.location = `${authLoginUrl}/oauth/authorize?client_id=HXJR&response_type=code&scope=HXJR&redirect_uri=${publicUrl}/auth`
      } else {
        let msg = res.message
        if (res.msg) {
          msg = res.msg
        }
        message.destroy()
        message.error(msg)
      }

      return response
    } else {
      return response
    }

  },
  (error) => {
    return Promise.reject(error)
  }
)

export default service
